<?php
class ReporterController extends AppController{
    var $name = 'Reporter';
    var $uses = array();

    function downloadFile($url){
        return file_get_contents($url);
    }

    function joinUrl($url){
        $result = isset($url['page'])?$url['page']:'';
        foreach($url as $k=>$v){
            if ($k != 'url' && $k != 'page')
                $result .= '&'.str_replace(array('&amp;','&'),'',$k).'='.$v;
        }
        return $result;
    }

    function composeUrl($url){
        $url = html_entity_decode($url);
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on')
            $src = 'https://';
        else
            $src = 'http://';
        if ($_SERVER['SERVER_PORT']==80 || $_SERVER['SERVER_PORT']==443)
            $src .= $_SERVER['SERVER_NAME'].'/';
        else
            $src .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/';
                
        if ($url[0] == '/')
            $url = substr($url,1);

        $src .= $url;
        $parts = explode('?',$src);
        if (count($parts) == 1)
            $sep = '?';
        else
            $sep = '&';
        $src .= $sep.'nolayout=&user='.$this->Session->read('Usuario.usuario').'&password='.$this->Session->read('Usuario.password').'&centro_dist_id='.$this->Session->read('Usuario.CentroDist.id').'&exercice='.$this->Session->read('Ejercicio.id').'&period='.$this->Session->read('Ejercicio.Actual.periodo_id').'&day='.$this->Session->read('Ejercicio.Actual.dia').'&clase_planilla_id='.$this->Session->read('Usuario.ClasePlanilla.id').'&tipo_planilla_id='.$this->Session->read('Usuario.TipoPlanilla.id');        
        return $src;
    }

    function extractName($url){
        $file = explode('?',$url);
        $file = $file[0];
        $file = $file[0] == '/' ? substr($file,1) : $file;
        $file = explode('/',$file);
        return low($file[0]) == 'adcsoft' ? $file[2] : $file[1];
    }

    function toPdf(){
        Configure::write('debug', 0);
        set_time_limit(0);
        $this->layout = false;
        $this->params['url']['page'] = $this->joinUrl($this->params['url']);
        
        $url = $this->composeUrl($this->params['url']['page']);
        $name = $this->extractName($this->params['url']['page']).'.pdf';
        $file = $this->downloadFile($url);

        $this->PrintHeaderDefault();
        $this->PrintFooterDefault();
        App::import('Vendor','mpdf44/mpdf');
        //limpiar página en caso de que haya una impresión innecesaria o por error
        ob_start();
        $html = ob_get_contents();
        ob_end_clean();

        //cargando objeto para crear pdf
        //$mpdf = new mPDF();
        //$mpdf=new mPDF('win-1252','A4','','',20,15,48,25,10,10);
        if(isset(AppController::$_mpdf)){
                $mpdf = AppController::$_mpdf;
        } else{
//                $mpdf=new mPDF('win-1252','LEGAL','','',10,10,20,10,10,10);
                $mpdf=new mPDF('win-1252','A4','8','Arial',10,10,20,10,10,10);
                $mpdf->SetDisplayMode('fullpage');
        }
        if(defined('_HEADER_DEFAULT_')){
                $htmlheader = '<table width="100%" cellpadding="0" cellspacing="0" style="border-bottom:solid 1px #000"><tr valign="middle"><td><img src="'. $this->path_webroot .'img\\logo.jpg" width="40" style="filter: alpha(opacity=50); opacity: .5" /><b>Corporación ADC</b></td></tr></table>';
                $mpdf->SetHTMLHeader($htmlheader);
        }
        if(defined('_FOOTER_DEFAULT_')){
                $mpdf->SetFooter('{DATE j-m-Y H:m} '.$this->_usuario['Tercero']['razon_social'].'| |{PAGENO}/{nb}');
        }

        $mpdf->SetProtection(array('print'));
        $mpdf->SetTitle($name);
        $mpdf->SetAuthor("ERP ADCSoft");

        //reemplazando rutas de imágenes
        $content_for_layout = str_replace('{path_webroot}', $this->path_webroot, $file);

        $mpdf->WriteHTML($content_for_layout);
//        $mpdf->Output();
        $mpdf->Output($name,'D');
        exit;


        
    }

    function toDoc(){
        Configure::write('debug', 0);
        set_time_limit(0);
        $this->layout = false;
        $this->params['url']['page'] = $this->joinUrl($this->params['url']);
        $url = $this->composeUrl($this->params['url']['page']);
        $name = $this->extractName($this->params['url']['page']).'.doc';        
        $file = $this->downloadFile($url);        		
        header('Content-type: application/msword');
        header('Content-Disposition: attachment; filename="'.$name.'"');
        echo $file;
        exit;
    }

    function toXls(){
        Configure::write('debug', 0);
        set_time_limit(0);
        $this->layout = false;
        $this->params['url']['page'] = $this->joinUrl($this->params['url']);
        $url = $this->composeUrl($this->params['url']['page']);
        $name = $this->extractName($this->params['url']['page']).'.xls';
        $file = $this->downloadFile($url);
        header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="'.$name.'"');
        
        echo utf8_decode($file);
        exit;
    }
}
?>
